package com.fenda.Controller;

import com.fenda.Dao.UserDao;
import com.fenda.Util.mybatisUtil;
import com.fenda.pojo.Student;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.IOException;

import java.util.List;

@Controller
public class UserController {
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
    @RequestMapping("/select")
    public String select(ModelMap model) throws IOException {
        SqlSession sqlSession = mybatisUtil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<Student> students =mapper.SelectAll();
        model.put("list",students);
        for (Student student : students) {
            System.out.println(student);
        }
        return "login";
    }
    @RequestMapping("/add")
    public String add(){
        return "add";
    }
    @RequestMapping("/add_commit")
    public String add_commit(String name,String age,String hobby) throws IOException {
        SqlSession sqlSession = mybatisUtil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.add(new Student(name,age,hobby));
        sqlSession.commit();
        return "redirect:index.jsp";
    }
    @RequestMapping("/delete")
    public String delete(int id) throws IOException {
        SqlSession sqlSession = mybatisUtil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int i = mapper.SelectId(id);
        if(i!=0){
            int delect = mapper.delect(i);
            sqlSession.commit();
        }
        return "redirect:index.jsp";
    }
    @RequestMapping("/update")
    public String update(int id) throws IOException {
        SqlSession sqlSession = mybatisUtil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        int i = mapper.SelectId(id);
        if( id==i ){
            return "update";
        }else{
            return "redirect:index.jsp";
        }

    }
    @RequestMapping("/updateto")
    public String updateto(String name,String age,String hobby) throws IOException {
        SqlSession sqlSession = mybatisUtil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.update(new Student(name,age,hobby));
        sqlSession.commit();
        System.out.println("修改成功");
        return "redirect:index.jsp";
    }
}
